package com.sencorsta.ids.core.tcp.opensocket.client;

import com.sencorsta.ids.core.application.Application;
import com.sencorsta.ids.core.configure.GlobalConfigure;
import com.sencorsta.ids.core.configure.TypeProtocol;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessage;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 回调服务器的反馈信息
 *
 * @author ICe
 */
@Sharable
public class OpenClientChannelHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //Out.warn(cause.getMessage());
        Out.info("OpenClient异常:", ctx.channel(), cause.getMessage());
        cause.printStackTrace();
        ctx.channel().close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Out.trace("OpenClient添加:", ctx.channel());
        //Out.debug("handlerAdded : ", ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //Out.debug("handlerRemoved : ", ctx.channel());
        Out.trace("OpenClient移除:", ctx.channel());
        SimulationUser user=ctx.channel().attr(GlobalConfigure.__KEY_SIMULATIONUSER).get();
        user.onRemoved();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object packet) throws Exception {
        //callback.handlePacket((Packet) msg);
        Out.trace("");
        Out.trace("OpenClient收到消息:", ctx.channel(), packet);
        if (packet instanceof OpenMessage){
            OpenMessage msg = (OpenMessage) packet;
            Out.trace(" " + msg.toStringPlus());
            switch (msg.header.type) {
                case TypeProtocol.TYPE_RES: {
                    SimulationUser user=ctx.channel().attr(GlobalConfigure.__KEY_SIMULATIONUSER).get();
                    user.onMessage(msg);
                    break;
                }
                case TypeProtocol.TYPE_HEAT: {
                    Out.trace("OpenServer心跳包:", ctx.channel(), " ", msg);
                    break;
                }
                default:
                    Out.trace("不支持的协议类型！", msg.header.type);
                    break;
            }
        }else {
            Out.trace(packet);
        }


    }

}